﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using Pixysoft.Framework.Logs.Core;

namespace Pixysoft.Framework.Logs.Controller
{
    /// <summary>
    /// 所有核心的writer的中央控制 保证每个相同路径的实例(logfilename)应用同一个writer.
    /// </summary>
    class WriterController
    {
        private static readonly System.Threading.ReaderWriterLock locker = new ReaderWriterLock();

        Dictionary<string, CoreLoggerWriter> writers = new Dictionary<string, CoreLoggerWriter>();


        private static volatile WriterController instance;

        private static object syncRoot = new Object();

        public static WriterController Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        instance = new WriterController();
                    }
                }

                return instance;

            }
        }

        /// <summary>
        /// 根据配置创建writer，如果不存在则新建
        /// </summary>
        /// <param name="setting"></param>
        /// <returns></returns>
        public CoreLoggerWriter CreateWriter(ILoggerSetting setting)
        {
            string logfilename = setting.GetLogFilePath() + setting.Filename + StringHelper.default_log_postfix;

            logfilename = logfilename.Trim().ToUpper();

            if (!Directory.Exists(setting.GetLogFilePath()))
            {
                Directory.CreateDirectory(setting.GetLogFilePath());
            }

            locker.AcquireWriterLock(Timeout.Infinite);

            try
            {
                if (writers.ContainsKey(logfilename))
                    return writers[logfilename];

                FileStream sw = File.Open(logfilename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

                StreamWriter writer = new StreamWriter(sw, Encoding.UTF8);

                CoreLoggerWriter logWriter = new CoreLoggerWriter(setting, writer);

                writers.Add(logfilename, logWriter);

                return logWriter;
            }
            finally
            {
                locker.ReleaseWriterLock();
            }
        }

        /// <summary>
        /// 根据配置移除writer，同时关闭
        /// </summary>
        /// <param name="setting"></param>
        /// <returns></returns>
        public bool RemoveWriter(ILoggerSetting setting)
        {
            string logfilename = setting.GetLogFilePath() + setting.Filename + StringHelper.default_log_postfix;

            logfilename = logfilename.Trim().ToUpper();

            locker.AcquireWriterLock(Timeout.Infinite);

            try
            {
                if (!writers.ContainsKey(logfilename))
                    return false;

                CoreLoggerWriter logWriter = writers[logfilename];

                logWriter.Flush();

                logWriter.Dispose();

                return writers.Remove(logfilename);
            }
            catch (Exception ex)
            {
                ConsoleHelper.Writeline(ex.ToString());

                return false;
            }
            finally
            {
                locker.ReleaseWriterLock();
            }

        }
    }
}
